﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TYStudioDemo.Interfaces;
using TYStudioDemo.DTO;

namespace TYStudioDemo.WebUI.Controllers
{
    public class SupplierController : BaseController
    {
        ISupplierService _supplierService;

        public SupplierController(ITYExceptionService tyExceptionService,
                                    ISupplierService supplierService)
        {
            _tyExceptionService = tyExceptionService;
            _supplierService = supplierService;

        }

        public ActionResult Index()
        {
            return View(_supplierService.GetAll());
        }

        public ActionResult Details(int id)
        {
            return View(_supplierService.GetByID(id));
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(SupplierViewModel vModel)
        {
            ActionResult result;
            try
            {
                throw new Exception("添加错误");
                _supplierService.Create(vModel);
                result = RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                //定义Dictionary用来存储非法的对象
                //根据实际需求，添加相应的数据，也可以不填任何数据
                Dictionary<string, object> parms = new Dictionary<string, object>();
                parms.Add("CompanyName",vModel.CompanyName);

                //返回错误信息，并将异常记入TYStudio_Logging数据库。
                ViewData["ErrorMessage"] = _tyExceptionService.HandleException(ex, parms, ex.Message);
                result = View(vModel);
            }

            return result;
        }

        public ActionResult Edit(int id)
        {
            return View(_supplierService.GetByID(id));
        }

        [HttpPost]
        public ActionResult Edit(SupplierViewModel vModel)
        {
            try
            {
                _supplierService.Update(vModel);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            return View(_supplierService.GetByID(id));
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                _supplierService.Delete(id);
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                //定义Dictionary用来存储非法的对象
                //根据实际需求，添加相应的数据，也可以不填任何数据
                Dictionary<string, object> parms = new Dictionary<string, object>();

                //返回错误信息，并将异常记入TYStudio_Logging数据库。
                ViewData["ErrorMessage"] = _tyExceptionService.HandleException(ex, parms, ex.Message);
                return View(_supplierService.GetByID(id));
            }
        }
    }
}
